<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" @click="Add(1,'0')">添加权限</el-button>
        </div>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          row-key="id"
        >
          <el-table-column
            fixed
            prop="name"
            label="名称"
            width="200"
          />
          <el-table-column
            prop="code"
            label="标识"
            width="200"
          />
          <el-table-column
            prop="description"
            label="描述"
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="200"
          >
            <template slot-scope="scope">
              <el-button v-if="scope.row.type===1" type="text" size="small" @click="Add(2,scope.row)">添加</el-button>
              <el-button type="text" size="small" @click="hEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- :title="isEdit? '编辑': '添加'" -->
      <!-- name="title" -->
      <el-dialog
        :title="isEdit ? `编辑${isChange}` : `添加${isChange}`"
        :visible.sync="showDialog"
        @close="closeFn"
      >
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="ruleForm.code" />
          </el-form-item>
          <el-form-item label="权限描述" prop="description">
            <el-input v-model="ruleForm.description" />
          </el-form-item>
          <el-form-item label="全线启用" prop="enVisible">
            <el-switch v-model="ruleForm.enVisible" />
          </el-form-item>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="showDialog=false">取消</el-button>

        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, delPermission, updatePermission, getPermissionDetail } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
export default {
  data() {
    const validCode = (rule, value, callback) => {
      const list = this.isEdit
        ? this.existedCodeList.filter(item => item !== this._code)
        : this.existedCodeList
      console.log('当前要校验的值', value, list)
      list.includes(value)
        ? callback(new Error(`权限标识 ${value} 已占用`))
        : callback()
    }
    const validName = (rule, value, callback) => {
      // console.log(this.existedNameList, value)
      // this.existedNameList.includes(value) ? callback(`权限名称 ${value}  已经占用`) : callback()
      const list = this.isEdit
        ? this.existedNameList.filter(item => item !== this._name)
        : this.existedNameList
      console.log('当前要校验的值', value, list)
      list.includes(value)
        ? callback(new Error(`权限名称 ${value} 已占用`))
        : callback()
    }

    return {
      isChange: '',
      existedCodeList: [], // 保存当前所有已经被占用的权限标识
      originList: [],
      isEdit: false, // 编辑 or 添加
      showDialog: false,
      tableData: [],
      curId: '',
      ruleForm: {
        name: '',
        code: '',
        description: '',
        enVisible: '0',
        type: '',
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' },
          { trigger: ['change', 'blur'], validator: validName }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' },
          { trigger: ['change', 'blur'], validator: validCode }
        ],
        description: [{ required: true, message: '请输入权限描述', trigger: 'blur' }]
      }
    }
  },
  computed: {
    existedNameList() {
      // this.originList = [{id, pid, name}]
      let curpId = this.curId
      if (this.isEdit) {
        const parent = this.originList.find(item => item.id === this.curId)
        curpId = parent.pid
      }
      // this.existedNameList = res.data.map(item => item.name)
      // console.log('当前已经有的权限名称', this.existedNameList)
      return this.originList.filter(item => item.pid === curpId).map(item => item.name.trim())
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    Add(type, row) {
      this.showDialog = true
      console.log(type, row.pid)
      this.ruleForm.type = type
      this.ruleForm.pid = row.pid
      this.curId = row.pid
      this.isEdit = false
      this.isChange = row.name === undefined ? '' : row.name
    },
    // 增加
    async  doadd() {
      const res = await addPermission(this.ruleForm)
      console.log('添加新的权限', res)
      this.showDialog = false
      this.loadPermissionList()
    },
    // 点击 编辑
    async  hEdit(row) {
      // 用户点击了编辑
      this.isEdit = true
      this.curId = row.id
      // 1.根据id获取详情
      const res = await getPermissionDetail(row.id)
      console.log('从后端返回的权限点', res)
      // 2. 填充在表单中
      this.ruleForm = res.data
      // 3.显示弹层
      this.isChange = row.name
      this.showDialog = true
      if (this.isEdit) {
        this._code = res.data.code
        this._name = res.data.name
      }
    },
    async doEdit() {
      const res = await updatePermission(this.ruleForm)
      console.log('编辑成功', res)
      // 1. 重发请求
      this.loadPermissionList()
      // 2. 关闭弹层
      this.showDialog = false
    },
    // 删除
    async doDel(id) {
      const res = await delPermission(id)
      console.log('删除权限', res)
      this.loadPermissionList()
      this.$message.success('操作成功')
    },
    hDel(id) {
      // alert(id)
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {
      })
    },
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          return
        }
        // 做编辑?做增加
        this.isEdit ? this.doEdit() : this.doadd()
      })
    },
    // 关闭
    closeFn() {
      this.ruleForm = {
        name: '',
        code: '',
        description: '',
        enVisible: '',
        type: this.type,
        pid: this.pid
      }
      this.$refs.ruleForm.resetFields()
    },
    // 获取权限列表
    async loadPermissionList() {
      const res = await getPermissionList()
      console.log('获取权限列表', res)
      this.existedCodeList = res.data.map(item => item.code)
      console.log('当前已经有的权限权限', this.existedCodeList)

      this.originList = res.data.map(item => {
        return {
          id: item.id,
          pid: item.pid,
          name: item.name
        }
      })
      const list = tranListToTreeData(res.data)
      this.tableData = list
      console.log('树状权限列表', this.tableData)
    }
  }
}
</script>

<style>

</style>
